package com.exartisan.molisasurvey;

import java.util.ArrayList;

import org.w3c.dom.Text;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.exartisan.bean.Data;
import com.exartisan.datamanager.SurveyManager;

public class SurveyActivity extends BaseActivity implements android.widget.CompoundButton.OnCheckedChangeListener  {
	// private TextView tvQnums;
	private TextView tvQuestion;
	private RadioGroup rdgAnswers;
	private LinearLayout layoutCheckbox;
	private EditText edtEssay;
	private int mCurrentQuiznumber;
	private int quiznums;
	private boolean isShowingSoftKeyboard;
	private int[] ansId;
	private ArrayList<int[]> ansIds;  
	private boolean submited;
	private boolean answerornot[];
	private String surveyName;
	private SurveyManager surveyManager;
	private ArrayList<Data> userData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_survey);
	}

	protected void initVariables() {
		isShowingSoftKeyboard = false;
		userData = new ArrayList<Data>(); 
		ansIds = new ArrayList<int[]>();
		surveyManager = SurveyManager.getInstance();
		mCurrentQuiznumber = 1;
		quiznums = 0;
		submited = false;

	}

	protected void initViews() {
		edtEssay = (EditText) findViewById(R.id.edt_essay);
		tvQuestion = (TextView) findViewById(R.id.tvQuestion);
		rdgAnswers = (RadioGroup) findViewById(R.id.rdgAnswers);
		rdgAnswers.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId != -1)
					{
					ansId[mCurrentQuiznumber - 1] = checkedId;
					switch (checkedId) {
					case 0:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "a", 0));
						break;
					case 1:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "b", 1));
						break;
					case 2:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "c", 2));
						break;
					case 3:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "d", 3));
						break;
					case 4:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "e", 4));
						break;
					case 5:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "f", 5));
						break;
					case 6:
						userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber-1, "g", 6));
						break;
					default:
						break;
					}
					}
				
			}
		});
		
		layoutCheckbox = (LinearLayout) findViewById(R.id.layout_checkbox);

	}

	protected void initActions() {
		setWillHotUpdateSettings(true);
		surveyName = this.getIntent().getExtras().getString("surveyName");
		quiznums = surveyManager.getsurveyContent(surveyName).size();
		ansId = new int[quiznums];
		for (int i = 0; i < quiznums; i++){
			userData.add(new Data(i, "", -1));
			int[] tmp = new int[surveyManager.getsurveyContent(surveyName).get(i).getAnswers().size()];
			for (int j=0; j<tmp.length; j++) tmp[j] = -1;
			ansIds.add(tmp);
			ansId[i] = -1;
		}
		if(getUser().getData() == null) {
			getUser().setData(userData);
			Log.d("data", "null");
		}
		else userData = getUser().getData();
		answerornot = new boolean[quiznums];
		for (int i = 0; i < answerornot.length; i++) {
			answerornot[i] = false;
		}
		
		findViewById(R.id.scroll_content).setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				if(isShowingSoftKeyboard) {
					hideSoftKeyboard();
					isShowingSoftKeyboard = false;
				}
				return false;
			}
		});
		
		edtEssay.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				isShowingSoftKeyboard = true;
				return false;
			}
		});
		edtEssay.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				userData.set(mCurrentQuiznumber - 1, new Data(mCurrentQuiznumber - 1, s.toString(), -1));
			}
		});
		
		showQuizz(mCurrentQuiznumber);
	}
	
	@Override
	protected void setUpActionBar() {
		super.setUpActionBar();
		getSupportActionBar().setDisplayShowHomeEnabled(false);
	}

	/**
	 * replace older Quiz by current Quiz and show it on screen
	 * 
	 * @param currentQuiznumber
	 *            - Integer
	 */
	private void showQuizz(int currentQuiznumber) {
		if (currentQuiznumber - 1 >= 0 && currentQuiznumber - 1 < quiznums) {

			String qHead = "Câu " + String.valueOf(currentQuiznumber) + ": ";
			tvQuestion.setText(new String(qHead
					+ surveyManager.getsurveyContent(surveyName)
							.get(currentQuiznumber - 1).getQuestion()));
			tvQuestion.setTextSize(18);
			int type = surveyManager.getsurveyContent(surveyName)
			.get(currentQuiznumber - 1).getType();
			if (type == 1) {
				getSupportActionBar().setTitle("I. Trắc nghiệm");
				rdgAnswers.removeAllViews();
				rdgAnswers.setVisibility(View.VISIBLE);
				layoutCheckbox.setVisibility(View.GONE);
				edtEssay.setVisibility(View.GONE);
				for (int i = 0; i < surveyManager.getsurveyContent(surveyName)
						.get(currentQuiznumber - 1).getAnswers().size(); i++) {
					RadioButton radioButton = new RadioButton(this);
					RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					params.height = LayoutParams.WRAP_CONTENT;
					params.width = LayoutParams.WRAP_CONTENT;
					params.rightMargin = 10;
					params.topMargin = 10;
					radioButton.setButtonDrawable(R.drawable.btn_radio_holo_light);
					radioButton.setTextSize(14);
					radioButton.setLayoutParams(params);
					radioButton.setText(new String(surveyManager
							.getsurveyContent(surveyName)
							.get(currentQuiznumber - 1).getAnswers().get(i)));
					radioButton.setId(i);
					if (submited)
						radioButton.setEnabled(false);
					rdgAnswers.addView(radioButton);
				}

				rdgAnswers.clearCheck();
				rdgAnswers.check(userData.get(mCurrentQuiznumber - 1).getAnsId());

			}
			
			else if(type == 2){
				getSupportActionBar().setTitle("II. Tự luận");
				rdgAnswers.setVisibility(View.GONE);
				layoutCheckbox.setVisibility(View.GONE);
				edtEssay.setVisibility(View.VISIBLE);
				edtEssay.setText(userData.get(mCurrentQuiznumber-1).getUserAnswer());
			}
			
			else if(type == 3){
				rdgAnswers.setVisibility(View.GONE);
				edtEssay.setVisibility(View.GONE);
				layoutCheckbox.setVisibility(View.VISIBLE);
				layoutCheckbox.removeAllViews();
				for (int i = 0; i < surveyManager.getsurveyContent(surveyName)
						.get(currentQuiznumber - 1).getAnswers().size(); i++) {
					CheckBox ckbAnswer = new CheckBox(this);
					ckbAnswer.setText(new String(surveyManager
							.getsurveyContent(surveyName)
							.get(currentQuiznumber - 1).getAnswers().get(i)));
					ckbAnswer.setId(i);
					if (ansIds.get(mCurrentQuiznumber - 1)[i] == 1) ckbAnswer.setChecked(true);
					else ckbAnswer.setChecked(false);
					ckbAnswer.setOnCheckedChangeListener(this);
					layoutCheckbox.addView(ckbAnswer);
				}
				
			}
			
		} else if (currentQuiznumber - 1 >= quiznums)
			mCurrentQuiznumber = quiznums;
		else if (currentQuiznumber - 1 < 0)
			mCurrentQuiznumber = 1;
	}


	public void onClickSubmit(View v) {
		showConfirmDialog();
	}
	
	private void finishSurvey(){
		Intent intent = new Intent(this, ResultActivity.class);
		startActivity(intent);
	}

	public void onClickNext(View v) {
		showQuizz(++mCurrentQuiznumber);
	}

	public void onClickPrevious(View v) {
		showQuizz(--mCurrentQuiznumber);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) ansIds.get(mCurrentQuiznumber - 1)[buttonView.getId()] = 1;
		else ansIds.get(mCurrentQuiznumber - 1)[buttonView.getId()] = -1;
	}
	
	private void showConfirmDialog(){
		AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
		restartAlertBuilder.setTitle("Thông báo");
		restartAlertBuilder
				.setMessage("Bạn muốn gửi kết quả ?");
		restartAlertBuilder.setCancelable(true);
		restartAlertBuilder.setPositiveButton("Có", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finishSurvey();
			}
		});
		restartAlertBuilder.setNegativeButton("Không", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		AlertDialog restartAlertDialog = restartAlertBuilder.create();
		restartAlertDialog.show();
	}
	
	private void hideSoftKeyboard() {
	    InputMethodManager inputMethodManager = (InputMethodManager)  this.getSystemService(SherlockActivity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
	}


}
